package org.example.car.service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.car.service.domain.Battery;
import org.example.car.service.domain.Machine;
import org.example.car.service.service.BatteryService;
import org.example.car.service.service.MachineService;

import java.util.List;

/**
 * @Author: Yanyanyu
 * @Date: 2024/6/30 15:34
 */
@Slf4j
public class MachineListener implements ReadListener<Machine> {

    private static final int BATCH_COUNT = 3;

    private List<Machine> machineList= ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private MachineService machineService;

    public MachineListener(MachineService machineService){
        this.machineService=machineService;
    }



    @Override
    public void invoke(Machine machine, AnalysisContext analysisContext) {
        System.out.println("解析的数据："+machine);

        machineList.add(machine);

        if(machineList.size()>BATCH_COUNT){

            machineService.insertAll(machineList);

            machineList=ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("解析完成");
        if(machineList.size()>0){
            machineService.insertAll(machineList);
        }
    }
}
